//
//  HMComposeViewController.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/25.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置背景色
        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
        
        
    }
    
    
    //添加子控件
    private func setupUI(){
        
        
        //添加导航栏的子控件
        setupNav()
        
        
        //添加
        view.addSubview(textView)
        view.addSubview(stackView)
         textView.addSubview(coll)
        
        
        
        //约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view)
        }
        
        //设置代理
        textView.delegate = self
        
        
        stackView.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        
        
        coll.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(100)
            make.leading.equalTo(self.view).offset(10)
            make.width.equalTo(screenWidth-20)
            make.height.equalTo(coll.snp_width)
            
        }

        
//        键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
        //接收通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleText:", name: "delete", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertImg:", name: "img", object: nil)
        
    }
    
    // MARK: -  实现添加图片到文本框的代理方法
    @objc private func insertImg(noti:NSNotification){
        
        let btn = noti.object as! HZAmotionBtn
        
        let model = btn.value!
        
        //发 emoji 表情微博
        if model.type == "1"{
            
            let str = ((model.code)! as NSString).emoji()
            
            textView.insertText(str)
            
        }else {
            
            //发表图片表情,(已封装到 textView 的分类中了)
            textView.insertImgText(model)
            
        }
        
        
        
        
        
    }
    
    // MARK: -  实现通知方法回删数据
    @objc private func deleText(noti:NSNotification){
        
        //回删数据的方法
        textView.deleteBackward()
        
     
    }
    
    
    
    //键盘弹出的通知方法
    @objc private func keyboardChangeFrame(noti:NSNotification){
        
//        print("下雨了")
        let rectObj = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!
        
        let ty = rectObj.CGRectValue.origin.y
        
        //计算出偏移量
        let y = ty-screenHight
        
        
        stackView.transform = CGAffineTransformMakeTranslation(0, y)
        
    }
    
    //文本框滚动的时候调用
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //收起键盘
        view.endEditing(true)

    }
    
    

    
     //添加导航栏的子控件
    private func setupNav(){
        
        //添加左控件
        let backItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "dismiss")
        
        navigationItem.leftBarButtonItem = backItem
        
        
        //添加右控件
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        //默认是不可点击状态
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        //设置中间的 title
        navigationItem.titleView = titleView
        
        
        
    }
    
    
    
    func dismiss(){
        
        textView.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    
    //懒加载控件
    private lazy var stackView:HZStackView = {
        
        
        //stackView的创建要使用 initWithFrame 的方法才行
       let stackView = HZStackView(frame: CGRectZero)
        
        
        //底部按钮闭包回调
        stackView.didBtnclosure = {[weak self] (btnType: HZStackViewBtnType)->() in
            
//            print(btnType)
            
            //如果是图片的点击闭包回调
            if btnType == .toolbar {
                
                self!.getImgAlbum()
//
            }
            
            //如果是表情的点击闭包回调
            if btnType == .emoticonbutton {
                
//                print("到了")
                self!.getAmoticon(btnType)
                
            }
            
            
            
            
        }
        
        
        return stackView
    }()
    
    
    //弹出表情键盘的方法
    func getAmoticon(btnType:HZStackViewBtnType){
        
        //成为第一响应者
        if !textView.isFirstResponder() {
            textView.becomeFirstResponder()
        }
        
        
        //设置表情键盘
        if textView.inputView == nil {
            
            textView.inputView = amotionView
            
        }else{
            
            textView.inputView = nil
           
        }
        
        //更新一下
        textView.reloadInputViews()
        
        //发送改变图标的通知
        NSNotificationCenter.defaultCenter().postNotificationName("amotion", object: (textView.inputView == nil))
        
    }
    
    
    
    
    
    
    //弹出相册的方法
    func getImgAlbum(){
        
//        print("天晴了")
        //创建相册控制器
        let imgPicker = UIImagePickerController()
        
        //设置代理
        imgPicker.delegate = self
        
        //打开到相册的页面
        imgPicker.sourceType = .SavedPhotosAlbum
        
        //弹出相册控制器
        self.presentViewController(imgPicker, animated: true, completion: nil)
    }
    
    
    // MARK: -  发送按钮的点击事件
    @objc private func sendMess() {
        
        //如果发送的图片框隐藏了说明只是发送文本微博
        if coll.hidden == true {
            
            //发送文字微博
            update()
        }else{
            
           //发送图片微博
            upload()
            
        }
        
    }
    
    //发送图片微博
    private func upload(){
        
        //请求的 url
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        //获取要发布的文本
        let text =  textView.emotionText!
        
        print(text)
        
        //请求参数
        let paras = ["access_token":HZOAuthVM.sharedVM.model?.access_token ?? "","status":text]
        
        //请求
        HZNetTools.sharedTools.uploadImg(urlString, parameter: paras, imgDict: ["pic":coll.imgArray.first!]) { (thing, error) -> () in
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送微博成功")
            
            
        }
        
    }
    
    
    //发文字微博
    private func update(){
        
        //请求的 url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        //获取要发布的文本
        let text =   textView.emotionText!
        
        //请求参数
        let paras = ["access_token":HZOAuthVM.sharedVM.model?.access_token ?? "","status":text]
        
        //请求
        HZNetTools.sharedTools.deliveryThing(requestMethod: .Post, urlString: urlString, parameter: paras) { (thing, error) -> () in
            
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送微博成功")
            
        }
        
        
    }
    
    
    
    // MARK: -  懒加载子控件
    private lazy var amotionView:HZAmotionView = {
        
       let amotionView = HZAmotionView()
        
        amotionView.frame.size = CGSize(width: screenWidth, height: 216)
        
        return amotionView
    }()
    
    
    
    
    private lazy var textView:HZTextView = {
        
       let textView = HZTextView()
        
          //设置垂直状态下的滚动效果
        textView.alwaysBounceVertical = true
        
        textView.placeholder = "这里的三鹿十八弯呀,昨天是一个大阳台"
        
        textView.font = UIFont.systemFontOfSize(16)
        
        return textView
    }()
    
    
    
    private lazy var titleView: UILabel = {
        
       let titleView = UILabel()
        
        // 指定行数
        titleView.numberOfLines = 0
        // 指定字体的颜色
        titleView.textColor = UIColor.blackColor()
        titleView.font = UIFont.systemFontOfSize(14)
        // 设置文字居中
        titleView.textAlignment = .Center


        //如果有姓名
        if let name = HZOAuthVM.sharedVM.model?.name {
            
            let text = "发微博\n\(name)"
            
            //设置 label 的符文本
            let range = (text as NSString).rangeOfString(name)
            let attText = NSMutableAttributedString(string: text)
            
            attText.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(10)], range: range)
            
            titleView.attributedText = attText
        }else{
            titleView.text = "发微博"
        }
        
        //让控件可内容一样大
        titleView.sizeToFit()
        
        return titleView
    }()
    
    
    
    
    
    private lazy var rightButton: UIButton = {
        let rightButton = UIButton()
        
        //监听发送按钮的用户点击事件
        rightButton.addTarget(self, action: "sendMess", forControlEvents: .TouchUpInside)
        
        rightButton.titleLabel?.font = UIFont.systemFontOfSize(14)
        rightButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        
        // 设置不同状态下的背景图
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的文字颜色
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSize(width: 45, height: 28)
        // 不启用
        // rightButton.enabled = false
        return rightButton
    }()

    lazy var coll:HZComCollView = {
        
        let coll = HZComCollView(frame: CGRectZero,collectionViewLayout: UICollectionViewFlowLayout())
        
        
        //闭包的回调
        coll.addImgClosure = {[weak self] in
            
            //弹出相册
            self!.getImgAlbum()
            
        }
        
        return coll
    }()
    
    
    
    //销毁时移除通知中心
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
        
        print("写微博销毁了")
        
    }
    
    

}


extension HMComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    
    
    //选择好了照片之后
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        //压缩图片
        let img = image.compressImg(200)
       
        //传递图片
        coll.giveImg(img)
        
        //设置代理方法之后要自己手动销毁这个控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}



extension HMComposeViewController:UITextViewDelegate {
    
    
    // MARK: -  当 textView的文本发生变化时调用
    func textViewDidChange(textView: UITextView) {
        
        //文本框有文字就让右控件可点击
         navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
}


